﻿using System.Security.Cryptography;

namespace Ofs.Shared
{
    internal sealed class FileHashAlgorithm : IFileHashAlgorithm
    {
        private readonly Func<HashAlgorithm> algorithmFactory;

        public FileHashAlgorithm(Func<HashAlgorithm> algorithmFactory)
        {
            this.algorithmFactory = algorithmFactory;
        }

        public async ValueTask<string> ComputeHashAsync(
            FileInfo fileInfo, CancellationToken cancellationToken = default)
        {
            using var algorithm = algorithmFactory();
            using var s = fileInfo.OpenRead();
            var result = await algorithm.ComputeHashAsync(s, cancellationToken);
            return Convert.ToHexString(result);
        }

        public void Dispose()
        {
            // Do nothing.
        }
    }
}
